/**
 * Created by dongchen on 16/4/4.
 */
var xml = require('node-xml');
var co = require('co');
var xml2js = require('xml2js');
var thunkify = require('thunkify');
// var xml2json = require('co-xml2js');
var xml2json = thunkify(xml2js.parseString);
var _  = require('lodash');
var moment = require('moment');
// 定义解析存储变量
var ToUserName = "";
var FromUserName = "";
var CreateTime = "";
var MsgType = "";
var Content = "";
var tempName = "";
//开始解析消息
var body = '{"code":0,"msg":null,"data":[{"prodOffName":"政企特套（4G）-漫入旅游项目专用20元/G（1506）","pStartTime":"20160401000000","pEndTime":"20160501000000","subAccuInfoList":[{"accuName":"流量全国1G/月","startTime":"20160201000000","endTime":"20170201000000","accuAmount":"1048576.00","usedAmount":"0.00","transferAccuAmount":"","transferUsedAmount":"","unitTypeId":"22"},{"accuName":"流量全国1G/月","startTime":"20160301000000","endTime":"20170301000000","accuAmount":"1048576.00","usedAmount":"0.00","transferAccuAmount":"","transferUsedAmount":"","unitTypeId":"22"},{"accuName":"流量全国1G/月","startTime":"20160401000000","endTime":"20170401000000","accuAmount":"1048576.00","usedAmount":"0.00","transferAccuAmount":"","transferUsedAmount":"","unitTypeId":"22"}]}]}';
var body2 = JSON.parse(body);
var xml = '<xml><ToUserName><![CDATA[gh_84b67eb6d654]]></ToUserName><FromUserName><![CDATA[oFs7Ovx2W2X9oEKWmXyzcQhSh7_0]]></FromUserName><CreateTime>1462986119</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[CLICK]]></Event><EventKey><![CDATA[V2000_QUARY_FLOW]]></EventKey></xml>';
co(function*(){
    console.log(1);
    var res = yield xml2json(xml, {explicitArray: false});
    console.log(res);
    co(function * (){
        console.log(3);
        yield xml2json(xml, {explicitArray: false});
        console.log(4);
    });
    console.log(2);
}).catch(function(err){
    console.log(err);
});

xml2js.parseString(xml, {explicitArray: false}, function(err, result){
    console.log(123 + result);
});
// var Content = buildFlowsetContent(body2);
// console.log(Content);

function buildFlowsetContent(data){
    if(data.code === 0){
        var flowset = data.data[0].subAccuInfoList;
        var total = 0;
        var result = '';
        _.each(flowset, function(monthData){
            var period = moment(monthData.startTime, 'YYYYMMDDhhmmss').format('YYYY年MM月');
            var flowLeft = +monthData.accuAmount;
            total += flowLeft;
            var fr = flowCal(flowLeft);

            result += `${period}结余:${fr.suitable},\n`
        });
        var tr = flowCal(total);
        result += `总计剩余流量:${tr.suitable}`;
        return result;
    }else{
        return data.msg;
    }
}

function flowCal(kb){
    var mb = (kb / 1024).toFixed(2);
    var gb = (mb / 1024).toFixed(2);

    var result = {
        kb : kb + 'K',
        mb : mb + 'M',
        gb : gb + 'G'
    };
    result.suitable = gb >= 1 ? result.gb : (mb >= 1 ? result.mb : result.kb);
    return result;
}
